package com.treeliked.udpdemo.cs;

import com.treeliked.udpdemo.model.Message;
import com.treeliked.udpdemo.page.p1.Client;
import com.treeliked.udpdemo.service.UdpService;
import com.treeliked.udpdemo.service.impl.ClientServiceImpl;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

/**
 * client
 *
 * @author lss
 * @date 2019-01-03, Thu
 */
public class UdpClient extends BaseClientServer {

    /**
     * 端口号
     */
    private int portNum;


    /**
     * 服务端端口号
     */
    private int serverPort;

    /**
     * socket
     */
    private DatagramSocket ds;

    /**
     * 上一次发送的消息
     */
    private Map<String, Message> messages = new HashMap<>(128);

    /**
     * 发送/接收服务
     */
    private UdpService service;

    public UdpClient(int portNum, int serverPort, Client client) throws SocketException {
        this.portNum = portNum;
        this.serverPort = serverPort;
        this.ds = new DatagramSocket(portNum);
        /**
         * 页面服务
         */
        service = new ClientServiceImpl(ds, UdpServer.DEFAULT_SERVER_PORT, client);
    }


    public void sendMessage(Message msg) throws IOException {
        messages.putIfAbsent(msg.getId(), msg);
        service.send(msg);
    }


    public void startReceive() throws IOException {
        service.startReceive(this);
    }

    public void stopReceive() throws IOException {
        service.stopReceive();
    }

    public int getPortNum() {
        return portNum;
    }

    public Message getMessageById(String msgId) {
        return messages.get(msgId);
    }

    // public void sendTestMessageEveryFiveSec() throws IOException {
    //     ThreadPoolExecutorFactory.getThreadPoolExecutor().execute(() -> {
    //         while (true) {
    //             Message msg = new Message(portNum, serverPort);
    //             try {
    //                 sendMessage(msg);
    //                 Thread.sleep(2000);
    //             } catch (IOException | InterruptedException e) {
    //                 e.printStackTrace();
    //             }
    //
    //         }
    //     });
    // }
}
